<template>
  <div class="upload-file">
    <el-button type="primary" :disabled="disabled" @click="openUpload">选取文件</el-button>
    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in newFileList" :key="index">
        <el-link @click="handleDownload(file)" :underline="false" target="_blank">
          <span class="el-icon-document">&nbsp;&nbsp;{{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index, file)" type="danger" :disabled="disabled">删除</el-link>
        </div>
      </li>
    </transition-group>
    <!-- 上传对话框 -->
    <el-dialog v-if="upload.open" :title="upload.title" v-model="upload.open" width="450px" append-to-body
      custom-class="dialogTable">
      <p></p>
      <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" :limit="limits"
        :on-change="handleChange" :on-error="handleUploadError" :on-remove="handleRemove" :on-exceed="handleExceed"
        :on-success="handleUploadSuccess" :show-file-list="true" :headers="upload.headers" class="upload-file-uploader"
        ref="uploads" :auto-upload="true" style="display: inline-block" :disabled="disabled" :fileType="fileType" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <!-- 上传提示 -->
          <div class="el-upload__tip text-center">
            <template v-if="showTip && isSpatialData == '0'">
              请上传
              <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
              <template v-if="fileType.length != 0"> 格式为 <b style="color: #f56c6c">{{ fileType.join(",") }}</b>
              </template>
              的文件
            </template>
            <template v-if="showTip && isSpatialData != '0'">
              <p>13类格网文件需要按照以下名称命名，且附属文件需要与shp文件名称统一。</p>
              <ul style="list-style: auto;text-align: left;">
                <li v-for="item in optionData" :key="item.dictItemCode">{{ item.dictItemName }}</li>
              </ul>
            </template>
            <template v-if="name">
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                @click="importTemplate(name)" v-if="isSpatialData == '0'">下载模板</el-link>
            </template>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="(fileList.length == 0) || (isSpatialData == '1' && uploadDisabled)"
            @click="submitFileForm">确 定</el-button>
          <el-button @click="(upload.open = false)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth"
import { ElMessageBox } from 'element-plus'
import { getListExcel, getListsShp, getListsTif } from '@/api/disasterManage/kilometerGrid/dataView'
import { getDataTyes } from '@/api/disasterManage/kilometerGrid/index.js'

const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 1000,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 100,
  },
  // 是否是空间数据
  isSpatialData: {
    type: Number,
    default: 0,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    //default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    default: () => [],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  code: {
    type: String,
    default: '',
  },
  name: {
    type: String,
    default: '',
  },
  isHasFile: {
    type: Number,
    default: 0,
  },
  ids: {
    type: Object,
    default: {},
  },
  isTif: {//是否应上传tif文件
    type: Boolean,
    default: false
  }
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const fileList = ref([]);
const openDrawer = ref(false);
const dataList = ref([]);
const titleList = ref([]);
const title = ref('');
const show = ref('0');
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
const limits = computed(
  () => {
    props.isSpatialData == 0 ? 1 : 10
  }
);
const uploadFileUrl = ref(props.isSpatialData == 0 ? import.meta.env.VITE_APP_BASE_API + "/attachment/uploadExcelFile" : import.meta.env.VITE_APP_BASE_API + "/attachment/uploadShpFile")// 上传的图片服务器地址
const newFileList = ref([]);
const dataVersion = ref();

const openPic = ref(false);
const openRep = ref(false);
const openShp = ref(false);
const propTitle = ref('');
const uploadDisabled = ref(true);
const id = ref('');
const parseDataCacheId = ref(null);
/*** 用户导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "tokrn " + getToken() },
  url: props.isSpatialData == 0 && props.isSpatialData != 2 ? import.meta.env.VITE_APP_BASE_API + "/attachment/uploadExcelFile" : import.meta.env.VITE_APP_BASE_API + "/attachment/uploadShpFile", // 上传的图片服务器地址
});

const data = reactive({
  form: {
    attach: [],
    reportAttach: []
  }
})
const { form } = toRefs(data)
watch(() => props.isSpatialData, val => {
  if (val == 0) {
    uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadExcelFile"
  } else {
    uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadShpFile"
  }
})
watch(() => props.isTif, val => {
  if (val) {
    uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadTifFile"
  } else {
    uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + "/attachment/uploadShpFile"
  }
})
watch(() => props.modelValue, val => {
  if (val) {
    let temp = 1;
    // 首先将值转为数组
    const list = Array.isArray(val) ? val : props.modelValue.split(',');
    // 然后将数组转为对象数组
    fileList.value = list.map(item => {
      if (typeof item === "string") {
        item = { name: item, url: item };
      }
      item.attachId = item.attachId || new Date().getTime() + temp++;
      item.name = item.attachName;
      item.url = item.attachPath;
      return item;
    });
    newFileList.value = fileList.value;
  } else {
    fileList.value = [];
    newFileList.value = fileList.value;
    return [];
  }
}, { deep: true });

// 确定
function submitFileForm() {
  if (props.isSpatialData == '1') {//空间数据
    let nameArr = [];
    fileList.value.forEach(item => {
      const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
      nameArr.push(typeName)
    })

    // if (props.isTif == false && (nameArr.includes('shp' && 'dbf' && 'prj' && 'shx' && 'cpg')) && props.isSpatialData == '1') {
    if (props.isTif == false && props.isSpatialData == '1') {
      newFileList.value = [];
      let id = [];
      fileList.value.forEach(item => {
        id.push(item.attachId)
      })
      proxy.$modal.loading("正在解析文件，请稍候...");
      getListsShp({ typeCode: props.code, fileIds: id.join(','), ...props.ids }).then(res => {
        proxy.$modal.closeLoading();
        if (res.data.code == 100001) {
          ElMessageBox.confirm(
            res.data.message,
            '消息',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
              parseDataCacheId.value = res.data.cacheId;
              emit('cacheId', { parseDataCacheId: parseDataCacheId.value });

              dataList.value = res.data.list;
              titleList.value = res.data.name;
              title.value = res.data.typeName;
              dataVersion.value = res.data.dataVersion;
              show.value = res.data.show;
              if (res.data.open == '1') {
                openDrawer.value = true;
                newFileList.value = fileList.value;
                emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
                upload.open = false;
              } else {
                newFileList.value = fileList.value;
                emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
                upload.open = false;
              }
            })
            .catch(() => {
              parseDataCacheId.value = null;
              emit('cacheId', { parseDataCacheId: parseDataCacheId.value });
              newFileList.value = [];
              emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: null, fieldEntry: null });
              upload.open = false;
            })
        } else {
          dataList.value = res.data.list;
          titleList.value = res.data.name;
          title.value = res.data.typeName;
          dataVersion.value = res.data.dataVersion;
          show.value = res.data.show;
          if (res.data.open == '1') {
            openDrawer.value = true;
            newFileList.value = fileList.value;
            emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
            upload.open = false;
          } else {
            newFileList.value = fileList.value;
            emit('sureUploadFile', { list: newFileList.value, tempVersionCode: dataVersion.value, parseDataCacheId: parseDataCacheId.value, fieldNum: res.data.fieldNum, fieldEntry: res.data.fieldEntry });
            upload.open = false;
          }
        }

      }).catch(err => {
        proxy.$modal.closeLoading();
      });
    }
  }
}

// 模板下载
function importTemplate(name) {
  proxy.download("/fxfzaqbz/data/downloadExcel", {
    fileName: name
  }, name);
};

function openUpload() {
  uploadDisabled.value = true;
  fileList.value = [];
  upload.title = "上传";
  upload.open = true;
}

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    const isTypeOk = props.fileType.some((type) => {
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }
  if (!props.fileType.length) {
    // 非第一次上传
    if (fileList.value.length) {
      var falg = fileList.value.some(item => {
        const name = item.name.slice(0, item.name.lastIndexOf("."));
        const fileName = file.name.slice(0, file.name.lastIndexOf("."));
        if (name != fileName) {
          const uploadName = fileList.value[0].name.slice(0, fileList.value[0].name.lastIndexOf("."));
          proxy.$modal.msgError(`文件名称不正确, 请上传名称为${uploadName}的文件!`);
          return true;
        }
      })
      if (falg) { return false; }
      let shp = 0;
      let dbf = 0;
      let prj = 0;
      let shx = 0;
      let cpg = 0;
      var falg1 = fileList.value.some(item => {
        let typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
        if (typeName == 'shp') {
          shp++;
          if (shp > 1) {
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg类型文件只能上传一个!`);
            return true;
          }
        }
        if (typeName == 'dbf') {
          dbf++;
          if (dbf > 1) {
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg类型文件只能上传一个!`);
            return true;
          }
        }
        if (typeName == 'prj') {
          prj++;
          if (prj > 1) {
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg类型文件只能上传一个!`);
            return true;
          }
        }
        if (typeName == 'shx') {
          shx++;
          if (shx > 1) {
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg类型文件只能上传一个!`);
            return true;
          }
        }
        if (typeName == 'cpg') {
          cpg++;
          if (cpg > 1) {
            proxy.$modal.msgError(`shp、dbf、prj、shx、cpg类型文件只能上传一个!`);
            return true;
          }
        }
      })
      if (falg1) { return false; }
    }
  }

  // 校检文件大小
  if (props.fileSize) {
    if (props.isSpatialData == '1') {
      var isLt = file.size / 1024 / 1024 < 500;
      if (!isLt) {
        proxy.$modal.msgError(`上传文件大小不能超过500MB!`);
        return false;
      }
    } else {
      var isLt1 = file.size / 1024 / 1024 < props.fileSize;
      if (!isLt1) {
        proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
        return false;
      }
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  upload.isUploading = true;
  number.value++;
  return true;
}

const fileNum = ref(0)
function handleChange(file, fileList) {
  fileNum.value = fileList.length
  fileList.value = fileList;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code == 200) {
    fileList.value.push({ attachId: res.data[0].attachId, name: file.name, url: res.data[0].attachPath });
    proxy.$modal.closeLoading();
    if (fileNum.value == fileList.value.length) {
      proxy.$modal.msgSuccess("上传文件成功");
    }
    emit('uploadFile', fileList.value);
    let nameArr = [];
    fileList.value.forEach(item => {
      const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
      nameArr.push(typeName)
    })

    uploadDisabled.value = false;
  }
}

// 删除文件
function handleDelete(index, file) {
  newFileList.value = [];
  emit('dels', [])
}

// 删除文件
function handleRemove(file, uploadFiles) {
  const index = fileList.value.findIndex(item => item.attachId === file.response.data[0].attachId)
  fileList.value.splice(index, 1)
}

// 下载文件
function handleDownload(file) {
  var query = {
    attachId: file.attachId,
    name: file.attachName
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

function getFileName(name) {
  return name
}

// 获取数据类别
const optionData = ref([])
function getType() {
  getDataTyes('jzwglgwlx').then(res => {
    optionData.value = res.data;
  })
}
getType()

defineExpose({
  fileList
})
</script>

<style scoped lang="scss">
.upload-file {
  width: 100%;
}

.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.el-upload-list__item-name {
  width: 310px !important;
  // white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
